package org.leetcode.middle.leetcode56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution {

    public int[][] merge2(int[][] intervals) {
        int m = intervals.length;

        Arrays.sort(intervals, Comparator.comparingInt(arr -> arr[0]));
        int start = intervals[0][0];
        int end = intervals[0][1];
        List<int[]> reslist = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            if (intervals[i][0] > end) {
                int[] item = {start, end};
                reslist.add(item);
                start = intervals[i][0];
                end = intervals[i][1];
            } else {
                end = Math.max(end, intervals[i][1]);
            }
        }

        int[] item = {start, end};
        reslist.add(item);

        int [][] res = new int[reslist.size()][];

        for (int i = 0; i < reslist.size(); i++) {
            res[i]=reslist.get(i);
        }

        return res;
    }

    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, (Array1, Array2) -> {
            return Array1[0] - Array2[0];
        });

        List<int[]> merged = new ArrayList<>();

        int[] currentArray = null;

        for (int i = 0; i < intervals.length; i++) {

            int Left = intervals[i][0];
            int Right = intervals[i][1];

            if (merged.size() != 0) {
                currentArray = merged.get(merged.size() - 1);
            }


            if (merged.size() == 0 || currentArray[1] < Left) {
                merged.add(new int[]{Left, Right});
            } else {
                currentArray[1] = Math.max(currentArray[1], Right);
            }

        }

        return merged.toArray(new int[merged.size()][]);
    }

    public static void main(String[] args) {
        int[][] test = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};

        Solution solution = new Solution();
        solution.merge(test);
    }
}
